package com.lz.service.file;

import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import com.lz.common.annotation.AnonymousAccess;
import com.lz.service.file.entity.FileEntity;
import com.lz.service.file.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    private static final String UPLOAD_PATH = "\n" +
            "<!DOCTYPE html>\n" +
            "</html>\n";
    @Resource
    private FileService fileService;

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        return fileService.saveFile(file);
    }

    @PostMapping("/test")
    @AnonymousAccess
    public String test() {
        return fileService.test();
    }

    //下载文件
    @PostMapping("/download")
    @AnonymousAccess
    public String download(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        try {
            FileEntity fileEntity = new FileEntity();
            fileEntity.setFileName("333");
            fileEntity.setPath("E:\\resource\\layout\\LZ-Word\\a.doc");
            fileEntity.setMimeType("doc");

            fileEntity.setFileName(fileName);


            File file = new File(fileEntity.getPath());
            if (!file.exists()) {
                throw new RuntimeException("读取文件失败");
            }

            log.debug("文件路径: {}", fileEntity.getPath()); // 添加日志
            log.debug("文件存在: {}", file.exists()); // 添加日志
            log.debug("文件 MIME 类型: {}", fileEntity.getMimeType()); // 添加日志

            if ("doc".equals(fileEntity.getMimeType()) || "docx".equals(fileEntity.getMimeType())) {

                Document doc = new Document(new FileInputStream(fileEntity.getPath()));

                // 将 .doc 文件转换为 .docx 文件，并写入 ByteArrayOutputStream
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                // 保存为 .docx 文件
                doc.save(outputStream, SaveFormat.DOCX);

                // 将.docx文件写入输出流
                response.reset();
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileEntity.getFileName() + "." + "docx", "UTF-8"));
                response.setContentType("application/octet-stream");
                response.setCharacterEncoding("UTF-8");
                // 将 ByteArrayOutputStream 的内容写入 HTTP 响应流
                try (OutputStream httpOutputStream = response.getOutputStream()) {
                    httpOutputStream.write(outputStream.toByteArray());
                    httpOutputStream.flush();
                }
                // 关闭输出流
                response.getOutputStream().close();
            } else {
                FileInputStream fileInputStream = new FileInputStream(file);
                byte buf[] = new byte[1024];
                int length = 0;
                response.reset();
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileEntity.getFileName() + "." + fileEntity.getMimeType(), "UTF-8"));
                response.setContentType("application/octet-stream");
                response.setCharacterEncoding("UTF-8");
                OutputStream outputStream = response.getOutputStream();
                // 输出文件
                while ((length = fileInputStream.read(buf)) > 0) {
                    outputStream.write(buf, 0, length);
                }
                // 关闭输出流
                outputStream.close();
                log.debug("文件读取成功，长度: {}", length); // 添加日志
                log.debug("文件输出成功"); // 添加日志
            }
        } catch (Exception e) {
            log.error("下载文件异常:", e);
        }
        return "success";
    }

}